package com.gitee.cui.nio.reactor;

import com.gitee.cui.nio.NioDemoConfig;
import com.gitee.cui.util.Dateutil;
import com.gitee.cui.util.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * 回显Reactor模式的客户端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/20 14:01
 **/
public class EchoClient {

    public static void main(String[] args) throws IOException {
        new EchoClient().start();
    }

    /**
     * 设置一些内容
     */
    private void start() throws IOException {
        InetSocketAddress address = new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT);
        SocketChannel socketChannel = SocketChannel.open(address);
        Logger.info("客户端连接成功");
        // 设置socketChannel为非阻塞模式
        socketChannel.configureBlocking(false);
        while (!socketChannel.finishConnect()) {
            // 自旋，一直到客户端连接到服务端为止
        }
        Logger.info("客户端启动成功");
        Processer processer = new Processer(socketChannel);
        new Thread(processer).start();
    }

    /**
     * 接收线程
     */
    private class Processer implements Runnable {
        private Selector selector;
        private SocketChannel socketChannel;
        public Processer(SocketChannel socketChannel) throws IOException {
            selector = Selector.open();
            this.socketChannel = socketChannel;
            // 注册selector的读写事件
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }

        @Override
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isReadable()) {
                            // 可读，从服务端通道将数据读取到buffer中，此时buffer为可写状态
                            ByteBuffer buffer = ByteBuffer.allocate(NioDemoConfig.SEND_BUFFER_SIZE);
                            SocketChannel channel = (SocketChannel) key.channel();
                            int length = 0;
                            while ((length = channel.read(buffer)) > 0) {
                                // 将buffer置为可读
                                buffer.flip();
                                Logger.info("server echo:" + new String(buffer.array(), 0, length));
                                buffer.clear();
                            }
                        } else if (key.isWritable()) {
                            // 可写，从控制台读取内容并写道服务端
                            ByteBuffer buffer = ByteBuffer.allocate(NioDemoConfig.SEND_BUFFER_SIZE);
                            Scanner scanner = new Scanner(System.in);
                            Logger.info("请输入发送内容：");
                            if (scanner.hasNext()) {
                                String next = scanner.next();
                                SocketChannel channel = (SocketChannel) key.channel();
                                buffer.put((Dateutil.getNow() + ">>" + next).getBytes(StandardCharsets.UTF_8));
                                // 将buffer置为可读，因为需要冲buffer中读取数据写道channel中
                                buffer.flip();
                                channel.write(buffer);
                                buffer.clear();
                            }
                        }
                    }
                    selectionKeys.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
